package com.yc.navy.springmvc.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yc.navy.springmvc.dto.OrderDetailDTO;
import com.yc.navy.springmvc.dto.ProductToOrderDTO;
import com.yc.navy.springmvc.exception.ProductStoreException;
import com.yc.navy.springmvc.mapper.ICartInfoMapper;
import com.yc.navy.springmvc.mapper.IOrderInfoMapper;
import com.yc.navy.springmvc.mapper.IOrderItemInfoMapper;
import com.yc.navy.springmvc.mapper.IProductInfoMapper;
import com.yc.navy.springmvc.service.IOrderInfoService;

@Service
public class OrderInfoServiceImpl implements IOrderInfoService{
	
	@Autowired
	private IOrderInfoMapper orderInfoMapper;
	
	@Autowired
	private IOrderItemInfoMapper orderItemInfoMapper;
	
	@Autowired
	private IProductInfoMapper productInfoMapper;
	
	@Autowired
	private ICartInfoMapper cartInfoMapper;
	
	@Transactional
	@Override
	public Map<String, Object> add(String[] cnos, String ano, Integer mno) {
		//生成订单编号
		String ono = UUID.randomUUID().toString();
			
		double totalPrice = 0;
		List<ProductToOrderDTO> list = productInfoMapper.findByOrder(cnos);
		for(ProductToOrderDTO pd : list) {
			System.out.println(pd.getNum() + "123456897");
			System.out.println(pd.getBalance() );
			if(pd.getNum() > pd.getBalance()) {
				throw new ProductStoreException();
			}
			totalPrice += pd.getNum() * pd.getPrice();
			System.out.println(totalPrice);
		}
				
		//添加订单 -> 构建订单对象
		Map<String, Object> orderInfo = new HashMap<String, Object>();
		orderInfo.put("ono", ono);
		orderInfo.put("ano", ano);
		orderInfo.put("mno", mno);
		orderInfo.put("totalPrice", totalPrice);
		orderInfoMapper.add(orderInfo);
				
		//添加订单详细 -> 订单详细对象
		Map<String, Object> itemInfo = new HashMap<String, Object>();
		itemInfo.put("ono", ono);
		itemInfo.put("cnos", cnos);
		orderItemInfoMapper.add(itemInfo);
				
		//扣仓库
		productInfoMapper.updateStore(cnos);
				
		//删除购物车
		cartInfoMapper.delete(cnos);
				
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("ono", ono);
		result.put("totalPrice", totalPrice);
		return result;
	}

	@Override
	public List<OrderDetailDTO> list(Integer mno) {
		return orderInfoMapper.list(mno);
	}

	@Override
	public int update(Map<String, Object> map) {
		return orderInfoMapper.update(map);
	}

}
